<?php
/**
 * Class WxPay
 * Desc  微信支付
 * Create on 2023/3/2 15:11
 * Create by wangyafang
 */

namespace app\api\controller\xyb;

use addons\epay\library\Collection;
use addons\epay\library\RedirectResponse;
use addons\epay\library\Response;
use addons\epay\library\Service;
use addons\wdxyh\library\Wxapp;
use app\api\model\xyb\Order;
use app\api\model\xyb\OrderReward;
use app\api\model\xyb\UserPlat;
use app\api\model\xyb\UserReceive;
use app\api\model\xyb\UserWechat;
use app\api\service\TemplateService;
use app\common\controller\Api;
use app\common\model\marketing\UsersMarketingCoupons;
use app\common\model\xyb\AdminBelong;
use app\common\model\xyb\OfficialPushMessageLog;
use think\cache\driver\Redis;
use think\Db;
use think\Log;
use Yansongda\Pay\Pay;
use app\admin\model\xyb\system\Config;

class WxPay extends Api
{
    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
    }

    /*订单回调*/
    public function notifyx()
    {
        $this->configObj = (new Config())->where('id', 1)->find();
        $param = $this->request->param();
        Log::info('订单微信支付回调');
        Log::info($param);

        if (!$order_id = (isset($param['out_trade_no']) ? $param['out_trade_no'] : 0)) {
            echo '订单不存在';
            return;
        }
        $type = $this->request->param('type');
        if (!$payment_res = Service::checkNotify($type)) {
            echo '签名错误';
            return;
        }
        $payment_data = $payment_res->verify();
        $trade_no = isset($payment_data['transaction_id'])?$payment_data['transaction_id']:'';
        Log::info($payment_res);
        $orderModel = new Order();
        $field = 'id,user_id,agent_id,type,pay_time,status,coupons_id,discount';
        $orders = $orderModel->where('id', $order_id)->field($field)->find();
        if ($orders['status'] > 0) {
            echo "success";
            return;
        }
        $orderModel->where('id', $order_id)->update(['status' => '1', 'pay' => '1', 'trade_order_no' => $trade_no, 'pay_time' => time()]);

        TemplateService::sendTemplateNewOrder($orders->agent_id, $order_id);
        echo "success";
        return;
    }

    /*小费回调*/
    public function reward()
    {
        $this->configObj = (new Config())->where('id', 1)->find();
        $param = $this->request->param();
        Log::info('小费微信支付回调');
        Log::info($param);
//        $type = $this->request->param('type');
//        if (!Service::checkNotify($type)) {
//            echo '签名错误';
//            return;
//        }
        $type = $this->request->param('type');
        if (!$payment_res = Service::checkNotify($type)) {
            echo '签名错误';
            return;
        }
        $payment_data = $payment_res->verify();
        $trade_no = isset($payment_data['transaction_id'])?$payment_data['transaction_id']:'';
        if (!$order_id = (isset($param['out_trade_no']) ? $param['out_trade_no'] : 0)) {
            echo '订单不存在';
            return;
        }
        if (!$orders = OrderReward::getOrderRewardInfo($order_id)) {
            echo '订单不存在';
            return;
        }
        $reward = floatval($orders['total_fee']);
        Db::startTrans();
        $res = (new Order())->where(['id' => $orders->order_id])->update(
            ['reward' => $reward, 'updatetime' => time(), 'total_fee' => Db::raw("total_fee+{$reward}")]
        );
        if (!$res) {
            Db::rollback();
            echo '订单不存在';
            return;
        }
        $update_result = OrderReward::where('id', $order_id)->update(['status' => '1', 'pay' => '1', 'trade_order_no' => $trade_no, 'pay_time' => time()]);
        if (!$update_result) {
            Db::rollback();
            echo '订单不存在';
            return;
        }
        Db::commit();
        return 'success';
    }

    /**
     * 提交退款订单
     * @param array|float $amount 订单金额
     * @param array|float $refund_money 退款金额
     * @param string $orderid 订单号
     * @param string $refund_sn 退款订单号
     * @param string $type 支付类型,可选alipay或wechat
     * @param string $remark 退款原因
     * @param string $notifyurl 通知回调URL
     * @param string $returnurl 跳转返回URL
     * @param string $method 支付方式
     * @return Response|RedirectResponse|Collection
     * @throws Exception
     */
    public static function submitRefund($amount, $refund_money, $orderid, $refund_sn, $type, $remark = null, $notifyurl = null, $returnurl = null, $method = 'app')
    {
        if (!is_array($amount)) {
            $params = [
                'amount' => $amount,
                'type' => $type,
                'notifyurl' => $notifyurl,
                'returnurl' => $returnurl,
                'method' => $method,
            ];
        } else {
            $params = $amount;
        }
        $type = isset($params['type']) && in_array($params['type'], ['alipay', 'wechat']) ? $params['type'] : 'wechat';
        $request = request();
        $notifyurl = isset($params['notifyurl']) ? $params['notifyurl'] : $request->root(true) . '/addons/epay/index/' . $type . 'notify';
        $config = Service::getConfig($type);
        $config['notify_url'] = $notifyurl;
        $config['return_url'] = $returnurl;
        $result = null;
        //退款参数
        $order_data = [
            'out_trade_no' => $orderid//原订单号
        ];
        if ($type == 'wechat') {
            //创建支付对象
            $pay = Pay::wechat($config);
            $total_fee = bcmul($amount, 100, 0);
            $refund_fee = bcmul($refund_money, 100, 0);
            $order_data = array_merge($order_data, [
                'out_refund_no' => $refund_sn,//退款订单号
                'total_fee' => $total_fee,//支付金额
                'refund_fee' => $refund_fee,//退款金额
                'refund_desc' => $remark,//退款原因
                'type' => $method  //支付方式
            ]);
        } else {
            $pay = Pay::alipay($config);
            $order_data = array_merge($order_data, [
                'out_request_no' => $refund_sn,//退款订单号
                'refund_amount' => $refund_money,
            ]);
        }
        $result = $pay->refund($order_data);

        //使用重写的Response类、RedirectResponse、Collection类
        if ($result instanceof \Symfony\Component\HttpFoundation\RedirectResponse) {
            $result = RedirectResponse::create($result->getTargetUrl());
        } elseif ($result instanceof \Symfony\Component\HttpFoundation\Response) {
            $result = Response::create($result->getContent());
        } elseif ($result instanceof \Yansongda\Supports\Collection) {
            $result = Collection::make($result->all());
        }
        return $result;
    }
}



 